<template>
  <view>
    <view class="search-box">
      <uni-search-bar class="search" @input="input" cancelButton="none" :radius="18" :bgColor="'#FFFFFF'" ></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResult.length !== 0">
      <view class="sugg-item" v-for="(item, i) in searchResult" :key="i" @click="gotoDetail(item)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons v-if="historyList.length !== 0" type="trash" size="17" @click="deleteHistory"></uni-icons>
      </view>
      <view class="history-list">
        <view class="tips" v-if="historyList.length === 0">暂无历史记录</view>
        <uni-tag v-else :text="item" v-for="(item, i) in historyList" :key="i" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        searchVal: '',
        searchResult: [],
        historyList: []
      };
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('historyList') || '[]')
    },
    methods: {
      // 搜索框输入事件
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(async () => {
          this.searchVal = e.value
          await this.getSearchList()
          this.saveSearchHistory()
        }, 500)
      },
      async getSearchList() {
        if (this.searchVal === '') {
          this.searchResult = []
          return
        }
        uni.hideKeyboard()
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch?query=' + this.searchVal)
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResult = res.message
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      saveSearchHistory() {
        // 方法一：实现历史数组中无重复项，且搜索项为第一位
        if (this.historyList.length !== 0) {
          this.historyList.some((item, i) => {
            if (item === this.searchVal) {
              this.historyList.splice(i, 1)
              return true
            }
          })
        }
        this.historyList.unshift(this.searchVal)
        uni.setStorageSync('historyList', JSON.stringify(this.historyList))
        /** 
         * 方法二：
         * (一) 实现搜索项位于第一位
         * 在计算属性 computed 节点中添加
         * computed: {
           * 页面中循环的 historyList 改成 histories
             histories() {
                * 由于数组是引用类型，不要基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
                * 应新建一个内存无关的数组 ，再进行 reverse 转化
                return [...this.historyList].reverse()
              }
            }
         * ---------------------------------------------
         * (二) 实现历史数组中无重复项
         * 1.将 Array 数组转化为 Set 对象
         * const set = new Set(this.historyList)
         * 2.调用 Set 对像的 delete 方法，移除对应的元素
         * set.delete(this.searchVal)
         * 3.调用 Set 对象中的 add 方法，像 Set 中添加元素
         * set.add(this.searchVal)
         * 4.将 Set 对象转化为 Array 数组
         * this.historyList = Array.from(set)
         * 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
         * uni.setStorageSync('historyList', JSON.stringify(this.historyList))
         * -------------------------------------------------------------------
         * 在 onLoad 生命周期函数中，加载本地存储的搜索历史记录：
         * onLoad() {
             this.historyList = JSON.parse(uni.getStorageSync('historyList') || '[]')
           }
         * */
      },
      deleteHistory() {
        this.historyList = []
        uni.setStorageSync('historyList', '[]')
      },
      gotoGoodsList(item) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + item
        })
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 9999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .goods-name {
        // 文字不允许换行
        white-space: nowrap;
        overflow: hidden;
        // 文字溢出后用'...'代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
      .tips {
        width: 100%;
        height: 40px;
        line-height: 40px;
        font-size: 12px;
        text-align: center;
      }
    }
  }
</style>
